/**
 * 设备树形菜单查询
 */
'use strict';

const conn = require('../../libs/DB/Conn');
const _ = require("underscore");

module.exports = async function (params) {
    let sql = `WITH RECURSIVE RecursiveCTE AS (
                        SELECT
                            CONCAT("d_",df.device_id) AS rangeId, df.range_id AS parentId,df.device_name AS rangeName,df.device_type AS type
                        FROM device_file df
                        INNER JOIN range_file drf ON drf.range_id = df.range_id AND drf.delete_sign = 1 AND drf.domain_id = ${params.userDomainId}
                        WHERE df.delete_sign = 1 ${params.deviceType ? `AND df.device_type = ${params.deviceType}` : ``} 
                        UNION
                        SELECT 
                            rf.range_id AS rangeId, rf.parent_id AS parentId, rf.range_name AS rangeName, 0 AS type
                        FROM range_file rf
                        JOIN RecursiveCTE rc ON rc.parentId = rf.range_id
                        WHERE rf.delete_sign = 1
                )
                    SELECT * FROM RecursiveCTE;SELECT domain_name AS domainName FROM domain_file WHERE domain_id = ${params.userDomainId}`;
    let result = await conn(sql);
    let rangeList = _.filter(result[0],function (data){
        return data.rangeId.split("_").length < 2;
    })
    let dataList = childrenListSort(0,rangeList);
    let domainName = result[1][0].domainName;
    return { success: true ,dataList:dataList,domainName:domainName};
};
function childrenListSort(childId,rangeList){
    let childrenList = _.filter(rangeList,{parentId:childId})
    for(const childIndex in childrenList){
        childrenList[childIndex].children = childrenListSort( parseInt(childrenList[childIndex].rangeId),rangeList);
    }
    return childrenList;
}